package com.pjbao.app.targetSale.self;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pjbao.app.targetSale.userInfo.UserInfo;
import com.pjbao.app.targetSale.userInfo.UserInfoDao;
import com.pjbao.microService.common.bean.CommonToolkitBean;
import com.pjbao.microService.common.bean.SimpleTemplateBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Created by 邱鹏 on 2016/10/11.
 */
@Service
public class SmsService {
    Logger logger = Logger.getLogger("[app][targetSale]");
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    CommonToolkitBean commonToolkitBean;
    @Autowired
    RestTemplate restTemplate;
    ObjectMapper mapper = new ObjectMapper();
    @Autowired
    UserInfoDao dao;

    /**
     * @return
     */
    public String sendMsg(String phone) throws IOException {
        String result = null;
        Map properties = commonToolkitBean.yamlConfigBean.yaml2Properties("config/targetSale.yml", "service.sms");
        java.lang.String url = properties.get("service.sms.url") + "";
        java.lang.String param = properties.get("service.sms.param") + "";
        Map argsMap = new HashMap<>();  
        argsMap.put("phone", phone);
        param = commonToolkitBean.template(param, argsMap, SimpleTemplateBean.TemplateType.DOLLAR);
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> formEntity = new HttpEntity<String>(param, headers);
        result = restTemplate.postForObject(url, formEntity, String.class);
        redisValidCode(result, phone);
        Map msgMap = new HashMap<>();
        msgMap.put("msg", "短信发送成功,请填写短信验证码");
        msgMap.put("code", "1");
        return mapper.writeValueAsString(msgMap);
    }

    private void redisValidCode(String result, String phone) throws IOException {
        Map smsMap = mapper.readValue(result, Map.class);
        if ("1".equals(smsMap.get("status"))) {
            Map dataMap = (Map) smsMap.get("data");
            Object validCode = dataMap.get("validateCodes");
            redisTemplate.opsForValue().set("target-sale:sms:" + phone, validCode);
            logger.info("手机号：" + phone + ",验证码：" + validCode);
        }
    }

    /**
     * @return
     */
    public String checkValidCode(UserInfo userInfo, String validCode) throws JsonProcessingException {
        String result = null;
        Object redisValidCode = redisTemplate.opsForValue().get("target-sale:sms:" + userInfo.getPhone());
        Map dataMap = new HashMap<>();
        if (validCode.equals(redisValidCode+"")) {
            mongoSave(userInfo);
            dataMap.put("msg", "感谢你的登记，请保持手机通畅，稍后客服联系您");
            dataMap.put("code", "1");
        }else{
            dataMap.put("code", "-1");
        }
        return mapper.writeValueAsString(dataMap);
    }

    public String mongoSave(UserInfo userInfo) throws JsonProcessingException {
        String time=(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date());
        userInfo.setCreateTime(time);
        dao.save(userInfo);
        return null;
    }
}
